package com.xiangge.crawler;

import com.xiangge.config.CrawlerProperties;
import com.xiangge.crawler.inter.JsoupCrawlerBaseServiceAdaptor;
import com.xiangge.db.pojo.SynthesizeCategory;
import com.xiangge.db.pojo.SynthesizeGoods;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lsy_server
 */
@Component
public class JingDongCrawlerService extends JsoupCrawlerBaseServiceAdaptor {
    @Override
    public void setOpenFlag(Boolean openFlag) {
        super.setOpenFlag(true);
    }

    @Override
    public void crawler() {
        if (!openFlag) {
            return;
        }
        try {
            CrawlerProperties.CrawlerSource jingDong = properties.getJingDong();
            List<SynthesizeCategory> level1s = categoryRepository.findAllByLevel(0);
            level1s.parallelStream().flatMap(level -> categoryRepository.findAllByPid(level.getId()).parallelStream())
                    .forEach(
                            category -> {
                                if (category.getJingdongInit()) {
                                    return;
                                }
                                for (int i = 1; i < PAGE_LIMIT; i = i + 2) {
                                    crawlerToDataBase(jingDong.getUrl(), i, category);
                                }
                                category.setJingdongInit(true);
                                categoryRepository.save(category);
                            }
                    );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void crawlerToDataBase(String url, int page, SynthesizeCategory category) {
        try {
            List<SynthesizeGoods> synthesizeGoods = crawlerGoods(url, page, category);
            goodsRepository.saveAll(synthesizeGoods);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<SynthesizeGoods> crawlerGoods(String crawlerUrl, Integer page, SynthesizeCategory category) throws IOException {
        crawlerUrl = crawlerUrl(crawlerUrl, category.getName(), page);
        Document document = Jsoup.connect(crawlerUrl).get();
        return analyze(document, category.getId());
    }

    @Override
    public List<SynthesizeGoods> analyze(Document document, Integer categoryId) {
        Elements liList = document
                .select("ul[class='gl-warp clearfix']")
                .select("li[class='gl-item']");
        return liList.stream().map(
                element -> {
                    try {
                        SynthesizeGoods goods = new SynthesizeGoods();
                        Elements select = element.select("div[class='p-img'] a");
                        Elements select1 = element.select("div [class='p-price']");
                        BigDecimal price = BigDecimal.valueOf(Double.parseDouble(select1.select("div[class='p-price'] strong i").text()));
                        String text = select1.select("div[class='p-price'] span[class='price-plus-1'] em").text();
                        BigDecimal vipPrice = StringUtils.isEmpty(text) ? null : BigDecimal.valueOf(Double.parseDouble(text.split("￥")[1]));
                        String title = select.attr("title");
                        if (title == null) {
                            return null;
                        }
                        String url = select.attr("href");
                        String picUrl = select.select("img").attr("src");
                        String data = url.substring(url.lastIndexOf("/") + 1);
                        long id = Long.parseLong(data.substring(0, data.indexOf(".")));
                        goods.setSource(SynthesizeGoods.GoodsSourceEnum.JINGDONG);
                        goods.setVisitUrl(url);
                        goods.setId(id);
                        goods.setPics(Collections.singletonList(picUrl));
                        goods.setTitle(title);
                        goods.setPrice(price);
                        goods.setVipPrice(vipPrice);
                        goods.setCategoryId(categoryId);
                        return goods;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
        ).filter(Objects::nonNull).collect(Collectors.toList());
    }
}
